package com.chenyi.web.controller.system;

import com.chenyi.common.annotation.Log;
import com.chenyi.common.constant.UserConstants;
import com.chenyi.common.core.controller.BaseController;
import com.chenyi.common.core.domain.entity.SysAdminRole;
import com.chenyi.common.core.domain.entity.SysAdmin;
import com.chenyi.common.core.domain.model.LoginAdmin;
import com.chenyi.common.core.page.TableDataInfo;
import com.chenyi.common.enums.BusinessType;
import com.chenyi.common.exception.BadRequestException;
import com.chenyi.common.exception.MessageException;
import com.chenyi.common.utils.AdminUtils;
import com.chenyi.common.utils.ServletUtils;
import com.chenyi.common.utils.StringUtils;
import com.chenyi.common.utils.poi.ExcelUtil;
import com.chenyi.framework.web.service.AdminTokenService;
import com.chenyi.system.service.ISysAdminPostService;
import com.chenyi.system.service.ISysAdminRoleService;
import com.chenyi.system.service.ISysAdminService;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户信息
 * 
 * @author wangkh
 */
@RestController
@RequestMapping("/admin/admin")
public class AdminController extends BaseController
{
    @Autowired
    private ISysAdminService userService;

    @Autowired
    private ISysAdminRoleService roleService;

    @Autowired
    private ISysAdminPostService postService;

    @Autowired
    private AdminTokenService tokenService;

    /**
     * 获取用户列表
     */
    @PreAuthorize("@admin.hasPermi('system:admin:list')")
    @GetMapping("/list")
    public ResponseEntity<TableDataInfo> list(SysAdmin user)
    {
        startPage();
        List<SysAdmin> list = userService.selectAdminList(user);
        return new ResponseEntity<>(getDataTable(list),HttpStatus.OK);
    }

    @Log(title = "管理员管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@admin.hasPermi('system:admin:export')")
    @GetMapping("/export")
    public ResponseEntity<Object> export(SysAdmin user)
    {
        List<SysAdmin> list = userService.selectAdminList(user);
        ExcelUtil<SysAdmin> util = new ExcelUtil<SysAdmin>(SysAdmin.class);
        return util.exportExcel(list, "用户数据");
    }

    @Log(title = "管理员管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@admin.hasPermi('system:admin:import')")
    @PostMapping("/importData")
    public ResponseEntity<Object> importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysAdmin> util = new ExcelUtil<SysAdmin>(SysAdmin.class);
        List<SysAdmin> userList = util.importExcel(file.getInputStream());
        LoginAdmin loginUser = tokenService.getLoginAdmin(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        String message = userService.importAdmin(userList, updateSupport, operName);
        return ResponseEntity.ok(message);
    }

    @GetMapping("/importTemplate")
    public ResponseEntity<Object> importTemplate()
    {
        ExcelUtil<SysAdmin> util = new ExcelUtil<SysAdmin>(SysAdmin.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@admin.hasPermi('system:admin:query')")
    @GetMapping(value = { "/", "/{userId}" })
    public ResponseEntity<Object> getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        Map<String,Object> data = Maps.newHashMap();
        List<SysAdminRole> roles = roleService.selectAdminRoleAll();
        data.put("roles", SysAdmin.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        data.put("posts", postService.selectAdminPostAll());
        if (StringUtils.isNotNull(userId))
        {
            data.put("data", userService.selectAdminById(userId));
            data.put("postIds", postService.selectAdminPostListByAdminId(userId));
            data.put("roleIds", roleService.selectAdminRoleListByAdminId(userId));
        }
        return ResponseEntity.ok(data);
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@admin.hasPermi('system:admin:add')")
    @Log(title = "管理员管理", businessType = BusinessType.INSERT)
    @PostMapping
    public ResponseEntity<Object> add(@Validated @RequestBody SysAdmin user)
    {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName())))
        {
            throw new MessageException("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            throw new MessageException("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            throw new MessageException("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(AdminUtils.getUsername());
        user.setPassword(AdminUtils.encryptPassword(user.getPassword()));
        userService.insertAdmin(user);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@admin.hasPermi('system:admin:edit')")
    @Log(title = "管理员管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public ResponseEntity<Object> edit(@Validated @RequestBody SysAdmin user)
    {
        userService.checkAdminAllowed(user);
        if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            throw new MessageException("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            throw new MessageException("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(AdminUtils.getUsername());
        userService.updateAdmin(user);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@admin.hasPermi('system:admin:remove')")
    @Log(title = "管理员管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public ResponseEntity<Object> remove(@PathVariable Long[] userIds)
    {
        userService.deleteAdminByIds(userIds);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@admin.hasPermi('system:admin:edit')")
    @Log(title = "管理员管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public ResponseEntity<Object> resetPwd(@RequestBody SysAdmin user)
    {
        userService.checkAdminAllowed(user);
        user.setPassword(AdminUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(AdminUtils.getUsername());
        userService.resetPwd(user);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@admin.hasPermi('system:admin:edit')")
    @Log(title = "管理员管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public ResponseEntity<Object> changeStatus(@RequestBody SysAdmin user)
    {
        userService.checkAdminAllowed(user);
        user.setUpdateBy(AdminUtils.getUsername());
        userService.updateAdminStatus(user);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
